package com.yongdin.minimalism.wifi;

/**
 * @ClassName: WiFiListActivity
 * @Description: java类作用描述
 * @Author: luweiming
 * @CreateDate: 2020/3/24 15:26
 * @Version: 1.0
 */

import android.content.Context;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.yongdin.minimalism.R;

import java.util.ArrayList;
import java.util.List;


public class WifiListActivity extends AppCompatActivity {

    private ArrayList<WifiInfo> wifiArray;
    private WiFiInfoAdapter wifiInfoAdapter;
    private ListView listWifi;

    private ProgressBar updateProgress;
    private TextView updateButton;
    private String wifiPassword = null;

    private WifiManager wifiManager;
    private WifiAdmin wiFiAdmin;
    private List<ScanResult> list;
    private ScanResult mScanResult;
    private StringBuffer sb = new StringBuffer();

    public void back(){
        finish();
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wifi_list);
        findViewById(R.id.iv_back).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        findViewById(R.id.tv_back).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        wiFiAdmin = new WifiAdmin(WifiListActivity.this);
        initLayout();

        getAllNetWorkList();
    }

    public void initLayout() {
        listWifi = (ListView) findViewById(R.id.listWiFi);

        // 刷新按钮和进度条
        updateProgress = (ProgressBar) findViewById(R.id.updateProgress);
        updateProgress.setVisibility(View.INVISIBLE);
        updateButton = (TextView) findViewById(R.id.updateButton);
        updateButton.setVisibility(View.VISIBLE);
        updateButton.setOnClickListener(new MyOnClickListener());

        Switch switchWifi = (Switch) findViewById(R.id.switchWifi);
        wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        switchWifi.setChecked(wifiManager.isWifiEnabled());
        switchWifi.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                                         boolean isChecked) {
                wifiManager.setWifiEnabled(isChecked);
                // 更新WiFi列表
                if (isChecked) {
                    listWifi.setVisibility(View.VISIBLE);
                    updateProgress.setVisibility(View.VISIBLE);
                    updateButton.setVisibility(View.INVISIBLE);
                    new Thread(new refreshWifiThread()).start();
                } else {
                    listWifi.setVisibility(View.GONE);
                }
            }
        });

    }

    final Handler refreshWifiHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    getAllNetWorkList();
                    updateProgress.setVisibility(View.INVISIBLE);
                    updateButton.setVisibility(View.VISIBLE);
                    break;

                default:
                    break;
            }
        }
    };

    public class refreshWifiThread implements Runnable {

        @Override
        public void run() {
            try {
                Thread.sleep(3000);
                Message message = new Message();
                message.what = 1;
                refreshWifiHandler.sendMessage(message);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    private class MyOnClickListener implements OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.updateButton:
                    updateButton.setVisibility(View.INVISIBLE);
                    updateProgress.setVisibility(View.VISIBLE);
                    new Thread(new refreshWifiThread()).start();
                    break;
                default:
                    break;
            }
        }

    }

    public void getAllNetWorkList() {

        wifiArray = new ArrayList<WifiInfo>();
        if (sb != null) {
            sb = new StringBuffer();
        }
        wiFiAdmin.startScan();
        list = wiFiAdmin.getWifiList();
        if (list != null) {
            for (int i = 0; i < list.size(); i++) {
                mScanResult = list.get(i);
                WifiInfo wifiInfo = new WifiInfo(mScanResult.BSSID,
                        mScanResult.SSID, mScanResult.capabilities,
                        mScanResult.level);
                wifiArray.add(wifiInfo);
            }

            wifiInfoAdapter = new WiFiInfoAdapter(getApplicationContext(),
                    wifiArray);
            listWifi.setAdapter(wifiInfoAdapter);

            //
            wiFiAdmin.getConfiguration();

            wifiInfoAdapter.setListener(new WiFiInfoAdapter.ClickListener() {
                @Override
                public void onItemClick(int position) {


                    // 连接WiFi
                   final String wifiItemSSID = list.get(position).SSID;
                    int wifiItemId = wiFiAdmin.IsConfiguration("\""
                            + list.get(position).SSID + "\"");
                    if (wifiItemId != -1) {
                        if (wiFiAdmin.ConnectWifi(wifiItemId)) {
                            // 连接已保存密码的WiFi
                            Toast.makeText(getApplicationContext(), "正在连接",
                                    Toast.LENGTH_SHORT).show();
                            updateButton.setVisibility(View.INVISIBLE);
                            updateProgress.setVisibility(View.VISIBLE);
                            new Thread(new refreshWifiThread()).start();
                        }
                    } else {
                        // 没有配置好信息，配置
                        WifiPswDialog pswDialog = new WifiPswDialog(
                                WifiListActivity.this,wifiItemSSID,
                                new WifiPswDialog.OnCustomDialogListener() {
                                    @Override
                                    public void back(String str) {
                                        wifiPassword = str;
                                        if (wifiPassword != null) {
                                            int netId = wiFiAdmin
                                                    .AddWifiConfig(list,
                                                            wifiItemSSID,
                                                            wifiPassword);
                                            if (netId != -1) {
                                                wiFiAdmin.getConfiguration();// 添加了配置信息，要重新得到配置信息
                                                if (wiFiAdmin
                                                        .ConnectWifi(netId)) {
                                                    // 连接成功，刷新UI
                                                    updateProgress
                                                            .setVisibility(View.VISIBLE);
                                                    updateButton
                                                            .setVisibility(View.INVISIBLE);
                                                    new Thread(
                                                            new refreshWifiThread())
                                                            .start();
                                                }
                                            } else {
                                                // 网络连接错误
                                            }
                                        } else {
                                        }
                                    }
                                });
                        pswDialog.show();
                    }
                }
            });
        }
    }

}